//
//  PhotoBrowserCell.swift
//  weibo
//
//  Created by cmh on 15/9/14.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

class PhotoBrowserCell: UICollectionViewCell {
    
    // 图片的URL
    var url: NSURL? {
        didSet{
            
            resetScoreView()
            // 开启指示器
            indicator.startAnimating()
            
            iconView.image = nil
            
            // 模拟延迟
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                
                self.iconView.sd_setImageWithURL(self.url, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed, SDWebImageOptions.RefreshCached]) { (image, error, _, _) -> Void in
                    
                    // 到这里说明图片已经下载完毕
                    self.indicator.stopAnimating()
                    
                    if error != nil {
                        
                        SVProgressHUD.showErrorWithStatus("你的网速不给力")
                    }
                    
                    self.setImagePosition()
                    
                }
            })
            
            
            
        }
        
    }
    
    // 重置scoreView的属性
    private func resetScoreView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置图片
    // 计算图片缩放后的尺寸
    private func displaySize(image: UIImage) -> CGSize {
        
        let sw = scrollView.bounds.width
        
        let scale = image.size.height / image.size.width
        
        let w = sw
        
        let h = scale * sw
        
        return CGSize(width: w, height: h)
        
    }
    
    // 计算图片显示的位置
    private func setImagePosition() {
        
        let size = displaySize(iconView.image!)
        
        iconView.frame = CGRect(origin: CGPointZero, size: size)
        
        let sw = scrollView.bounds.height
        
        // 短图
        if size.height < sw {
            
            let y = (sw - size.height) * 0.5
            
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
            
        } else { // 长图
            
            scrollView.contentSize = size
            
        }
        
    }
    
    // MARK: - 设置UI
    private func setupUI() {
        
        contentView.addSubview(scrollView)
        scrollView.addSubview(iconView)
        contentView.addSubview(indicator)
        
        // 自动布局
        var rect = bounds
        rect.size.width -= 20
        
        scrollView.frame = rect
        
        indicator.center = scrollView.center
        
        prepareScrollView()
    }
    
    // 准备scrollView
    private func prepareScrollView() {
        
        // 设置代理
        scrollView.delegate = self
        
        // 设置缩放比例
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        
    }
    
    // 懒加载控件
    lazy var iconView: UIImageView = UIImageView()
    
    private lazy var scrollView: UIScrollView = UIScrollView()
    
    private lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
}

// MARK: - scrollView的代理方法
extension PhotoBrowserCell: UIScrollViewDelegate {

    // scrollView的缩放
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return iconView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        var offsetX = (scrollView.bounds.width - iconView.frame.width) * 0.5
        var offsetY = (scrollView.bounds.height - iconView.frame.height) * 0.5
        
        offsetX = offsetX > 0 ? offsetX : 0
        offsetY = offsetY > 0 ? offsetY : 0
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)

    }

}